package com.java.oauth.controller;

import com.java.oauth.service.AuthService;
import com.java.oauth.util.AuthToken;
import com.java.oauth.util.CookieUtil;
import com.java.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

//@RestController
//@RequestMapping(value = "/user")
public class AuthController {
	//Cookie存储的域名
	@Value("${auth.cookieDomain}")
	private String cookieDomain;
	//Cookie生命周期
	@Value("${auth.cookieMaxAge}")
	private int cookieMaxAge;
	@Autowired
	AuthService authService;

	@PostMapping("/login")
	public R login(String username, String password) {
		if (StringUtils.isEmpty(username)) {
			throw new RuntimeException("用户名不允许为空");
		}
		if (StringUtils.isEmpty(password)) {
			throw new RuntimeException("密码不允许为空");
		}
		//申请令牌
		AuthToken authToken = authService.login(username, password);

		//用户身份令牌
		String access_token = authToken.getAccess_token();
		//将令牌存储到cookie
		saveCookie(access_token);

		return R.ok();
	}

	/***
	 * 将令牌存储到cookie
	 */
	private void saveCookie(String token) {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", token, cookieMaxAge, false);
	}
}
